package SaveServlet.manager;

import com.lyq.bean.Course;
import com.lyq.bean.Student;
import com.lyq.bean.mySql.ElectC_Sql;
import com.lyq.bean.service.C_Service;
import com.lyq.bean.service.S_Service;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/assignCourse")
public class AssignCourse_Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        try {
            String courseId = request.getParameter("courseId");

            // 1. 根据courseId查找课程信息
            Course course = new C_Service().seek_CS(courseId);
            if (course == null) {
                out.print("{\"success\": false, \"message\": \"课程不存在\"}");
                return;
            }

            // 2. 获取专业和届数
            int majorId = course.getMajorId();
            int yearId = course.getYearId();

            // 3. 查找符合条件的学生
            List<Student> students = new S_Service().getStudentsByMajorAndYear(majorId, yearId, new ArrayList<>());

            if (students.isEmpty()) {
                out.print("{\"success\": false, \"message\": \"没有找到符合条件的学生\"}");
                return;
            }

            // 4. 批量插入选课记录
            int successCount = 0;
            for (Student student : students) {
                boolean result = (new ElectC_Sql()).electC_Sql(course.getNo(), course.getName(),
                        student.getNo());
                if (result) successCount++;
            }

            out.print("{\"success\": true, \"message\": \"成功为" + successCount + "名学生分配课程\"}");

        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\": false, \"message\": \"分配失败: " + e.getMessage() + "\"}");
        }
    }
}